//api,服务器路径
var host = "真实ip域名";//例如 https://free.qudone.com/free/
//var host = "测试ip域名地址";
/**
 * demo使用案例
 * main.js注入
 * import netUtil from "./utils/netUtil.js"
 * Vue.prototype.$netrequest = netUtil
 * 
 * 在页面调用
 * this.$netrequest.post("", params, function (res) {
      if (res.code === 200) {
        
      }else{
		  
	  }
    })  // 请求结束
 */
/**
 * 供外部post请求调用
 * 登录专调用，没有设置请求头
 */
function requestlogin(url, params, onSuccess) {
  var header = {}
  header['content-type'] = 'application/x-www-form-urlencoded'
  //console.log(header)
  request_login(url, params, "POST", onSuccess, header);
}
/**
 * 没有设置请求头的方法
 */
function postAjax(url, params, onSuccess) {
  var header = {}
  header['content-type'] = 'application/json'
  requestjson(url, params, "POST", onSuccess, header);
}
/**
 * post请求表单格式请求，携带token请求头
 */
function post(url, params, onSuccess) {
  var header = {}
  header['content-type'] = 'application/x-www-form-urlencoded'
  header['Authorization'] = uni.getStorageSync('token')
  //console.log(header)
  request(url, params, "POST", onSuccess, header);
}
/**
 * post请求JSON格式请求，携带token请求头
 */
function postjson(url, params, onSuccess) {
  var header = {}
  header['content-type'] = 'application/json'
  header['Authorization'] = uni.getStorageSync('token')
  requestjson(url, params, "POST", onSuccess, header);
}
/**
 * post单文件上传请求，携带token请求头
 */
function danUploadFile(url, params, onSuccess, onFailed) {
  var header = {}
  // header['content-type'] = 'multipart/form-data'
  header['Authorization'] = uni.getStorageSync('token')
  uploadFile(url, params, "POST", onSuccess, header);
}
/**
 * post表单请求验证验证码，，携带token请求头和JSESSIONID
 */
function postcode(url, params, onSuccess) {
  var header={}
  header['content-type'] = 'application/x-www-form-urlencoded'
  header['Authorization'] = uni.getStorageSync('token')
  header['Cookie'] = "JSESSIONID=" + uni.getStorageSync('sessionid')
  //console.log(header)
  requestcode(url, params, "POST", onSuccess,header);
}
/**
 * post josn格式请求验证验证码，，携带token请求头和JSESSIONID
 */
function postjsoncode(url, params, onSuccess) {
  var header = {}
  header['content-type'] = 'application/json'
  header['Authorization'] = "Bearer "+uni.getStorageSync('token')
  header['Cookie'] = "JSESSIONID=" + uni.getStorageSync('sessionid')
  //console.log(header)
  requestcode(url, params, "POST", onSuccess, header);
}
/**
 * 供外部get请求调用
 */
function get(url, params,onSuccess) {
  var header={}
  header['content-type'] = 'application/json'
  header['Authorization'] = "Bearer "+uni.getStorageSync('token')
  request(url, params, "GET", onSuccess, header);
}

/**
 * 请求更新token
 */
function refreshtoken(callBack) {
  var _this = this
  var header = {}
  header['content-type'] = 'application/x-www-form-urlencoded'
  uni.request({
    url: host + "uaa/oauth/token",
    data: gettoken(),
    method: "POST",
    header: header,
    success: function (ress) {
      console.log(ress)
      if (ress.data.code === 200){
        uni.setStorageSync('token', ress.data.data.accessToken)
        callBack(ress.data.data)
      }else{
        uni.showModal({
          title: '提示',
          content: "加载失败，凭证刷新失败，请退出小程序重试！",
          showCancel: false,
          success: function (res) { }
        })
      }   
    },
    fail: function (error) {
      uni.showModal({
        title: '提示',
        content: "加载失败，请检查网络然后退出小程序重试！",
        showCancel: false,
        success: function (res) { }
      })
    }
  })
}


/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式：GET/POST
 * @onStart 开始请求,初始加载loading等处理
 * @onSuccess 成功回调
 */
function request(url, params, method, onSuccess, headerd) {
  var _this = this
  uni.showLoading({
    title: '加载中...',
    mask: true
  });
  uni.request({
    url: host + url,
    data: dealParams(params),
    method: method,
    header: headerd,
    success: function (ress) {
      uni.hideLoading()
      console.log(ress.data)
      var res = ress.data
      if (res.code === 100000 || res.code === 100003||res.code=="1000001"){
        refreshtoken(function (ressss) {
          post(url, params, onSuccess, onFailed)
        })
      }else{
        onSuccess(res);
      }
    },
    fail: function (error) {
      uni.hideLoading()
      uni.showModal({
        title: '提示',
        content: "加载失败，请检查网络然后退出小程序重试！",
        showCancel: false,
        success: function (res) { }
      })
    }
  })
}

function request_login(url, params, method, onSuccess, headerd) {
  var _this = this
  uni.showLoading({
    title: '加载中...',
    mask: true
  });
  uni.request({
    url: host + url,
    data: dealParams(params),
    method: method,
    header: headerd,
    success: function (ress) {
      uni.hideLoading()
      var res = ress.data
      console.log(res)
      if (res.code === 100000 || res.code === 100003||res.code=="1000001") {
        uni.showModal({
          title: '提示',
          content: "登录凭证丢失，请退出小程序重新进入！",
          showCancel: false,
          success: function (res) { }
        })
      }else{
        onSuccess(res);
      }
      
    },
    fail: function (error) {
      uni.hideLoading()
      uni.showModal({
        title: '提示',
        content: "加载失败，请检查网络然后退出小程序重试！",
        showCancel: false,
        success: function (res) { }
      })
    }
  })
}
/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式：GET/POST
 * @onStart 开始请求,初始加载loading等处理
 * @onSuccess 成功回调
 */
function requestjson(url, params, method, onSuccess, headerd) {
  var _this = this
  uni.showLoading({
    title: '加载中...',
    mask: true
  });
  uni.request({
    url: host + url,
    data: dealParams(params),
    method: method,
    header: headerd,
    success: function (ress) {
      uni.hideLoading()
      var res = ress.data
      if (res.code === 100000 || res.code === 100003||res.code=="1000001") {
        refreshtoken(function (ressss) {
          postjson(url, params, onSuccess, onFailed)
        })
      } else {
        console.log(res)
        onSuccess(res)
      }
    },
    fail: function (error) {
      uni.hideLoading()
      uni.showModal({
        title: '提示',
        content: "加载失败，请检查网络然后退出小程序重试！",
        showCancel: false,
        success: function (res) { }
      })
    }
  })
}

function requestcode(url, params, method, onSuccess,headerd) {
  var _this = this
  uni.showLoading({
    title: '加载中...',
    mask: true
  });
  uni.request({
    url: host + url,
    data: dealParams(params),
    method: method,
    header: headerd,
    success: function (ress) {
      uni.hideLoading()
      var res = ress.data
      if (res.code === 100000 || res.code === 100003||res.code=="1000001") {
        refreshtoken(function (ressss) {
          var hhhhh = headerd
          hhhhh['Authorization'] = uni.getStorageSync('token')
          requestcode(url, params, method, onSuccess, onFailed, hhhhh)
        })
      } else {
        console.log(res)
        onSuccess(res)
      }
    },
    fail: function (error) {
      uni.hideLoading()
      uni.showModal({
        title: '提示',
        content: "加载失败，请检查网络然后退出小程序重试！",
        showCancel: false,
        success: function (res) { }
      })
    }
  })
}

/**
 * function: 单文件上传
 * @params 请求参数
 */
function uploadFile(url, params, method, onSuccess,headerd) {
	var _this = this
	uni.showLoading({
	  title: '上传文件中...',
	  mask: true
	});
  uni.uploadFile({
    url: host + url,
    filePath: params,
    name: 'file',
    method: method,
    header: headerd,
    success: function (ress) {
      uni.hideLoading()
      var res = JSON.parse(ress.data)
      if (res.code === 100000 || res.code === 100003||res.code=="1000001") {
        uni.showModal({
          title: '提示',
          content: res.data,
          showCancel: false,
          success: function (res) { }
        })
      } else {
        console.log(res)
        onSuccess(res)
      }
    },
    fail: function (error) {
      uni.hideLoading()
      uni.showModal({
        title: '提示',
        content: "加载失败，请检查网络然后退出小程序重试！",
        showCancel: false,
        success: function (res) { }
      })
    }
  })
}
/**
 * function: 根据需求处理请求参数：添加固定参数配置等
 * @params 请求参数
 */
function dealParams(params) {
  return params;
}
function gettoken(){
  const app = getApp()
  // console.log(global.uuid)
  var data ={}
  data["username"] = app.globalData.uuid+"|wx"
  data["password"] = app.globalData.appid
  data["grant_type"] = "password"
  data["client_id"] = "miniapp"
  data["client_secret"] = "miniapp1234!@#$"
  data["scope"] = "miniapp"
  return data;
}

module.exports = {
  post: post,
  get: get,
  postjson: postjson,
  postAjax:postAjax,
  danUploadFile:danUploadFile,
  postcode: postcode,
  postjsoncode: postjsoncode,
  refreshtoken: refreshtoken,
  requestlogin: requestlogin,
  host:host
}